package org.ling.xuan.util;

import cn.hutool.core.util.StrUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class CmdUtil {
    /**
     * 执行命令
     *
     * @param workingDir dir工作
     * @param cmdCommand cmd命令
     * @return {@link String}
     * @throws IOException          ioexception
     * @throws InterruptedException 中断异常
     */
    public static String executeCommand(String workingDir, String cmdCommand) throws IOException, InterruptedException {
        // 创建ProcessBuilder对象，传入命令及参数
        ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", cmdCommand);
        // 设置工作目录
        processBuilder.directory(new File(workingDir));
        // 启动进程
        Process process = processBuilder.start();
        // 获取进程的输出流
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        // 读取输出信息并拼接为字符串
        StringBuilder output = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line).append(System.lineSeparator());
        }
        // 等待进程执行完成
        process.waitFor();
        String result = output.toString();
        int i =process.exitValue();
        if(i==0) {
            if (StrUtil.isNotBlank(result)) {
                result = result.replace("\r\n", "\n").trim();
            }
            return result;
        }else{
            throw new RuntimeException("执行"+cmdCommand+"失败,输出信息:"+result);
        }
    }
}
